package com.wk.masterNode;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import com.wk.database.DB_Mysql;
import com.wk.database.SlaveMachine;
import com.wk.database.entity.Query;
import com.wk.job.Job;
import com.wk.job.Task;
import com.wk.job.heartbeat.master.JobStateHeartbeatHandler;
import com.wk.net.heartbeat.handler.receivers.TcpReceiver;

public class JobStateHeartbeatHandlerBuilder {
	public static final String TABLE = "t_business_computing_resource_management";
	public static final String MACHINE_IP = "resource_ip_address";
	public static final String MACHINE_STATE = "machine_status";

	/* 将会占有资源，需手动关闭（调用方法closeListener()） */
	public void listen(int port) throws IOException {
		receiver = new TcpReceiver(port);
		receiver.listen();
	}

	public void loadSlaves() {
		Query<SlaveMachine> query = new Query<>(SlaveMachine.class);
		try {
			query.connect(DB_Mysql.getConnection());
			machines = query.execute();
		} catch (SQLException e) {
			e.printStackTrace();
			return;
		}
	}

	public void dumpObservedSlaves() {
		System.out.println("从节点：");
		for (SlaveMachine machine : machines) {
			System.out.println(machine.toString());
		}
	}

	public JobStateHeartbeatHandler makeHandler(ConcurrentHashMap<String, Job> observedJobs,
			ConcurrentHashMap<Integer, Task> tasks, int checkPeriod, int absenceTolerance) {
		if (receiver == null || machines == null) {
			return null;
		}

		handler = new JobStateHeartbeatHandler(receiver, observedJobs, tasks, checkPeriod, absenceTolerance);
		for (SlaveMachine machine : machines) {
			handler.observe(machine.ip, machine.isOnline());
		}

		return handler;
	}

	public void closeListener() {
		receiver.close();
	}

	private JobStateHeartbeatHandler handler;

	private TcpReceiver receiver;
	private List<SlaveMachine> machines;
}
